package com.njust.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.njust.Util.RedisUtil;
import com.njust.constant.Constant;
import com.njust.domain.dto.MessageDTO;
import com.njust.domain.dto.MessagePageQueryDTO;
import com.njust.domain.dto.UserPageQueryDTO;
import com.njust.domain.po.Message;
import com.njust.domain.po.User;
import com.njust.domain.vo.PageQueryVO;
import com.njust.domain.vo.UserPageQueryVO;
import com.njust.exception.AccountHasLogin;
import com.njust.exception.AddMessageError;
import com.njust.exception.AdminOperateException;
import com.njust.exception.DeleteAccountFailedException;
import com.njust.mapper.AdminMapper;
import com.njust.mapper.MessageMapper;
import com.njust.mapper.UserMapper;
import com.njust.service.AdminService;
import com.njust.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Author Imak
 * @Date 2024/11/8 15:56
 * @管理员service
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页查询
     * @param userPageQueryDTO
     * @return
     */
    public PageQueryVO pageQuery(UserPageQueryDTO userPageQueryDTO) {
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());

        Page<UserPageQueryVO> page=adminMapper.pageQuery(userPageQueryDTO);
//        判断用户状态
        for(UserPageQueryVO user:page){
            String uIdStr=redisUtil.getCacheObject(user.getUserName());
            if(uIdStr==null){//离线
                user.setState(Constant.OFFLINE);
            }else{
                user.setState(Constant.ONLINE);
            }
        }
        long total=page.getTotal();
        List<UserPageQueryVO> records=page.getResult();

        return new PageQueryVO(total,records);
    }

    /**
     * 更新状态
     * @param state
     * @param uId
     */
    public void updateState(int state, int uId) {
        User user=userMapper.selectById(uId);

        if(state==Constant.ONLINE||user==null){
            throw new AdminOperateException("操作异常");
        }
//        下线即清除缓存
        redisUtil.deleteObject(user.getUserName());
    }

    /**
     * 删除账号
     * @param uId
     */
    public void deleteAcc(int uId) {
        User user=userMapper.selectById(uId);
        int result = userMapper.deleteById(uId);
        if(result <= 0){
            throw new DeleteAccountFailedException("注销失败");
        }
        redisUtil.deleteObject(user.getUserName());
    }

}
